<template>
  <div>
    <label-order-alert v-if="data.labelOrder && data.labelOrder.status !== 2"></label-order-alert>
    <combination-order-alert v-if="data.combinationOrder && data.combinationOrder.status === 0"></combination-order-alert>

    <el-card class="header-card">
      <div class="item">
        <p class="font-bold">用户：{{data.userAccount}}</p>
        <p class="font-bold" v-if="false">
          {{$t('table.warehouse')}}：{{ data.typeStr }}
          <template v-if="data.officialWarehouseName">
            ({{data.officialWarehouseName}})
          </template>
        </p>
        <p class="font-bold" v-if="false">
          {{$t('收件仓库')}}：{{data.warehouseName}}
          <template v-if="data.freeStorageDay">
            <span class="mgl10">{{$t('免仓期')}}: {{data.freeStorageDay}} {{$t('天')}}</span>
          </template>
        </p>
        <p class="font-bold">{{$t('table.shipmentNumber')}}：{{ data.shipmentNo }}</p>


        <p class="font-bold">发货计划：
          <el-link
            :underline="false"
            type="primary"
            @click="jumpPage('shippingPlanInfo', {id: data.planId})"
          >
            {{data.shippingPlanNo}}
          </el-link>
        </p>

        <p class="font-bold" v-if="showLabelOrder">{{ $t('table.贴标单号') }}：
          <el-link
            :underline="false"
            type="primary"
            @click="jumpLabelOrderInfoV2(data.labelOrder.id,true)"
          >
            {{data.labelOrder.labelNo}}
          </el-link>
        </p>

        <p class="font-bold" v-if="data.combinationOrder">{{ $t('table.组装单号') }}：
          <el-link
            :underline="false"
            type="primary"
            @click="jumpCombinationInfoV2(data.combinationOrder.id, true)"
          >
            {{data.combinationOrder.combinationNo}}
          </el-link>
        </p>
        <p>
          货件类型：{{getShipmentTypeStr2(data.shipmentType)}}
        </p>
        <template v-if="data.planType === PLAN_TYPE_FL()">
          <p>
            报关方式：{{getShipmentBGMethodStr(data.BGMethod)}}
          </p>
        </template>

        <template v-if="isShipmentFullType">
          <p>
            <span class="mgr20">官方仓库：{{data.officialWarehouseName}}</span>
            <span class="mgr20">店铺ID：{{data.accountId}}</span>
            <span class="mgr20">货件ID：{{data.fullShipmentId}}</span>
          </p>
        </template>



        <p v-if="data.cancel">{{ $t('table.作废时间') }}：{{data.cancelTime || '-'}}</p>
        <p>
          <span style="margin-right: 20px">{{ $t('table.Expected number of SKU types to be received') }}：{{data.exSkuNum}}</span>
          <span class="mgr20">预计入库箱子总数：{{data.exBoxNum}}</span>
          <span>{{ $t('table.Expected quantity of goods to be received') }}：{{data.exGoodsNum}}</span>
        </p>
        <p v-if="data.status2 === FINISHED_SHELVES()">
          <span class="mgr20">实际入库SKU种数：
            <strong
            :class="{
              'true-number': data.rlSkuNum !== data.exSkuNum
              }"
            >
              {{data.rlSkuNum}}
            </strong>
          </span>
          <span class="mgr20">
            实际入库箱子总数：
            <strong
              :class="{
              'true-number': data.exBoxNum !== data.rlBoxNum
              }"
            >
              {{data.rlBoxNum}}
            </strong>
          </span>
          <span>实际入库商品总数量：
            <strong
              :class="{
              'true-number': data.rlGoodsNum !== data.exGoodsNum
              }"
            >
              {{data.rlGoodsNum}}
            </strong>
          </span>
        </p>

        <p v-if="false">
          <span>
            {{$t('shipment.总货值（元）')}}:
            <template v-if="data.status === 0">
              {{ data.exSumGoodsValue }}
            </template>
            <template v-else>
              {{ data.rlSumGoodsValue }}
            </template>
          </span>
        </p>
        <p v-if="false">
          <span>{{$t('table.上架费用（元）')}}：
            <template v-if="data.status === 1">
              {{data.rlListingFee}}
            </template>
            <template v-else>
              {{data.exListingFee}}
            </template>
          </span>
        </p>
        <p v-if="data.planType === PLAN_TYPE_FL()">
          <span class="mgr20">总重量：{{data.sumWeight}}kg</span>
          <span class="mgr20">总方数：{{data.sumSquareNumber}}</span>
          <span class="mgr20">总计费重：{{data.sumCalWeight}}</span>
        </p>
      </div>

    </el-card>
    <div class="mgt20" v-if="data.planType === PLAN_TYPE_FL()">
      <el-radio-group v-model="currentContainerId">
        <el-radio-button
          v-for="item in containerList"
          :key="item.label"
          :label="item.label"
        >
          {{item.text}}
        </el-radio-button>
      </el-radio-group>
    </div>

    <div>
      <h4>货件进度</h4>
      <template v-if="data.planType === PLAN_TYPE_FL()">
        <shipment-steps :data="data" :history="data.history ? data.history : []"></shipment-steps>
      </template>
      <template v-else-if="data.planType === PLAN_TYPE_MW()">
        <shipment-steps2 :data="data" :history="data.history ? data.history : []"></shipment-steps2>
      </template>
    </div>

    <div>
      <h4>{{ $t('shipment.shipmentDetail') }}</h4>
      <div class="box-header">
        <div class="mgb10 font-red f13 left">
          <template v-if="data.status2 === WAIT_FL_RECEIVE()">
            如客户填写或硬件测量的货件重量尺寸与实际不符，您可以点击下方列表的「修改」按钮手动修改
          </template>
        </div>
        <div class="right">
          <div style="display: flex;">
            <el-input v-model.trim="searchBoxText" placeholder="搜索箱唛/SKU" style="width: 200px"></el-input>
            <template v-if="data.status2 === WAIT_FL_RECEIVE() && isFirstLegRole()">
              <el-button type="primary" @click="allReceive" class="mgl20">全部已接收</el-button>
            </template>
            <template v-if="data.status2 === WAIT_SORTING() && isInboundSortingRole() && data.planType === PLAN_TYPE_MW()">
              <el-button type="primary" @click="allSorted" class="mgl20">全部已分拣</el-button>
            </template>
          </div>

        </div>
      </div>

      <div class="table">
        <shipment-box-table :table-data="boxLabelListBySearch" :shipment="data" :hidden-table-data="hiddenSomeBox"></shipment-box-table>
      </div>
    </div>



    <div>
      <h4>{{ $t('shipment.productDetails') }}</h4>
      <div class="table">
        <shipment-goods-table :shipment-goods="shipmentGoods" :shipment="data"></shipment-goods-table>
      </div>
    </div>
    <div class="table-tips" v-if="showTips">
      <p>{{$t('shipment.detailsText1')}}</p>
      <p class="font-red">{{ $t('shipment.detailsText2') }}</p>
      <p class="font-red">{{$t('shipment.当前页面未贴标商品的实际入库整箱/混装数量仅做记录用，实际入库数量以对应贴标工单的“实际贴标数量”为准')}}</p>
      <p>{{ $t('shipment.detailsText5') }}</p>
    </div>

    <div v-if="data.shipmentType === 'offline_delivery'">
      <div class="mgt20" v-if="data.userAddress">
        <span style="font-weight: bold">
          配送地址：
        </span>
        <div>
          <address-box :address="data.userAddress"></address-box>
        </div>
      </div>
    </div>

    <div class="remark">
      <h4>{{$t('shipment.step4Text10')}}：</h4>
      <el-input
        type="textarea"
        :placeholder="$t('shipment.step4Text11')"
        v-model="data.remark"
        autosize
      >
      </el-input>
    </div>

  </div>
</template>

<script>
import {saveShipmentBox, saveShipmentBoxV2, saveShipmentGoods} from "@/api/shipment";
import {jumpCombinationInfo, jumpLabelOrderInfo, jumpPage} from "@/utils/jumpView";
import {
  FINISHED_SHELVES,
  FINISHED_SORTING, getShipmentBGMethodStr,
  getShipmentStatus2Str,
  getShipmentStatusStr,
  getShipmentTypeStr,
  getShipmentTypeStr2, HALF_SHELVES, WAIT_FL_RECEIVE, WAIT_SORTING
} from "@/utils/shipment";
import {getLabelStatusStr} from "@/utils/labelOrder";
import DispositionInventoryLocationInfo from "@/views/stock/components/DispositionInventoryLocationInfo.vue";
import MLCodeColumn from "@/views/stock/components/MLCodeColumn.vue";
import LabelOrderAlert from "@/views/labelOrder/components/LabelOrderAlert.vue";
import GoodsSizeSpan from "@/views/stock/components/GoodsSizeSpan.vue";
import {deepCopy, getPlatformShortNameByAccountNum, getPlatformTextColor} from "@/utils";
import CombinationOrderAlert from "@/views/shipment/components/CombinationOrderAlert.vue";
import {getCombinationStatus} from "@/utils/combination";
import ShipmentBoxTable from "@/views/shipment/components/ShipmentBoxTable.vue";
import ReElTable from "@/components/Common/ReElTable.vue";
import ShipmentGoodsTable from "@/views/shipment/components/ShipmentGoodsTable.vue";
import ShipmentSteps from "@/views/shipment/components/ShipmentSteps.vue";
import {STATUS_RECEIVED, STATUS_SORTED} from "@/utils/boxLabel";
import {getContainerStatusStr, WAIT_MAKE_CABINET} from "@/utils/container";
import {PLAN_TYPE_FL, PLAN_TYPE_MW} from "@/utils/shippingPlan";
import ShipmentSteps2 from "@/views/shipment/components/ShipmentSteps2.vue";
import TestWS from "@/views/test/TestWS.vue";
import {isFirstLegRole, isFLOperate, isInboundSortingRole, isMiddleRole, isOneShippingRole} from "@/utils/common";
import {Socket} from "@/socket/Socket";
import {EventBus} from "@/utils/eventBus";
import AddressBox from "@/views/shipment/components/AddressBox.vue";
import {containerBoxAllInstall} from "@/api/container";
import {allReceive, shipmentAllSorted} from "@/api/shipmentV2";

export default {
  name: "ShipmentInfoView",
  components: {
    AddressBox,
    ShipmentSteps2,
    ShipmentSteps,
    ShipmentGoodsTable,
    ShipmentBoxTable,
    CombinationOrderAlert,
    LabelOrderAlert,
  },
  watch: {
    containerList(){
      if(this.data.planType === PLAN_TYPE_FL){
        this.currentContainerId = this.containerList[0]?.label
      }
    },
    currentContainerId(){
      this.$emit('update:containerId', this.currentContainerId)
    },
    containerId(){

      if(typeof this.containerId === 'number'){
        if(this.containerId !== this.currentContainerId){
          this.currentContainerId = this.containerId
        }
      }
    }
  },
  props:{
    data: {
      type: Object,
      required: true,
    },
    shipmentBox: {
      type: Array,
      required: true,
    },
    shipmentGoods:{
      type: Array,
      required: true,
    },
    shipmentBoxLabelList: {
      type: Array,
      required: true,
    },
    // 硬件模式
    HWMode:{
      type: Boolean,
      default: false,
    },
    containerId: {
      type: [Number, String],
      default: '',
    }
  },
  computed:{
    accountName(){
      const accountName = [];
      this.data.accountList.forEach(item=>{
        accountName.push(item.showName)
      })
      return accountName.join('、')
    },
    checkConfirm(){
      return this.shipmentBox.some(item => typeof item.rlBoxNum  === 'undefined') || this.shipmentGoods.some(item=>{
        if(this.data.type === 1){
          return false
        }
        return item.rlGoodsNum === undefined
      })
    },
    // 是否展示贴标工单相关数据
    showLabelOrder(){
      return this.data && this.data.labelOrder
    },
    // 是否显示操作栏相关类型的数据 没有贴标工单 或者贴标工单已完成的展示
    showEditNum(){
      return this.data && ( (this.data.labelOrder && this.data.labelOrder.status === 2) || !this.data.labelOrder || this.data.subType === 2)
    },
    showShipmentGoodsData(){
      const startIndex = (this.showShipmentGoodsParams.page - 1) * this.showShipmentGoodsParams.pageSize; // 起始索引位置
      return this.shipmentGoods.slice(startIndex, startIndex + this.showShipmentGoodsParams.pageSize); // 返回切片后的结果
    },
    containerList(){
      const arr = [];
      if(this.data.status2 !== WAIT_FL_RECEIVE){
        if(this.waitCabinetBoxList.length > 0){
          arr.push({label: WAIT_MAKE_CABINET, text: '国内待装柜'})
        }
        if(this.receivedBoxList.length > 0){
          arr.push({label: STATUS_RECEIVED, text: '国内未接收'})
        }
        if(this.data.containerList){
          this.data.containerList.forEach(item=>{
            const obj = {
              label: item.id,
              text: '货柜-' + (item.containerNo || item.flightNo ||  item.containerName) + `(${getContainerStatusStr(item.status)})`
            }
            arr.unshift(obj)
          })
        }
      }

      return arr;
    },
    boxLabelList(){
      let arr = this.shipmentBoxLabelList
      if(typeof this.currentContainerId === 'number'){
        return  arr.filter(item=> item.containerId === this.currentContainerId)
      }else if(typeof this.currentContainerId === 'string'){
        switch (this.currentContainerId){
          case STATUS_RECEIVED:
            return this.receivedBoxList
          case WAIT_MAKE_CABINET:
            return this.waitCabinetBoxList
        }
      }
      return arr;
    },
    boxLabelListBySearch(){
      if(!this.searchBoxText){
        return this.boxLabelList
      }
      return this.boxLabelList.filter(item=>{
        return item.boxId.includes(this.searchBoxText) || item.sku.includes(this.searchBoxText)
      })
    },
    receivedBoxList(){
      return this.shipmentBoxLabelList.filter(item=> item.isReceived === 0)
    },
    waitCabinetBoxList(){
      return this.shipmentBoxLabelList.filter(item=> !item.containerId && item.isReceived === 1 && this.data.status2 !== WAIT_FL_RECEIVE)
    },
    currentContainerRow(){
      if(!this.data.containerList){
        return null
      }
      return this.data.containerList.find(item=> item.id === this.currentContainerId)
    },
    // 已分拣后的状态才显示提示
    showTips(){
      const status = this.data.status2
      if(!status){
        return false
      }
      const arr = [FINISHED_SORTING, HALF_SHELVES, FINISHED_SHELVES];
      return arr.includes(status)
    },
    // 展示所有箱唛
    hiddenSomeBox(){
      let flag = true
      if(this.data.status2 === WAIT_FL_RECEIVE && isFirstLegRole()){
        return false
      }
      if(this.currentContainerRow && this.currentContainerRow.status === FINISHED_SORTING){
        return false
      }
      // 如果是移仓
      if(this.data.planType === PLAN_TYPE_MW){
        if(isInboundSortingRole()){
          if(this.data.status2 === WAIT_SORTING){
            return false;
          }
        }
        if(this.data.status2 === FINISHED_SORTING){
          return false
        }

      }
      return flag
    },
    // 是否官方仓类型
    isShipmentFullType(){
      return this.data.shipmentType === 'mkd_full' || this.data.shipmentType === 'mkd_cbt_full'
    },
  },
  data(){
    return {
      boxLoading: false,
      knowSku: 0,
      showShipmentGoodsParams: {
        page: 1,
        pageSize: 100,
      },
      currentContainerId: '',
      socket: null,
      searchBoxText: '', // 箱唛搜索
    }
  },
  created() {
    if(typeof this.containerId === 'number'){
      if(this.containerId !== this.currentContainerId){
        this.currentContainerId = this.containerId
      }
    }
  },
  methods:{
    isInboundSortingRole,
    WAIT_SORTING() {
      return WAIT_SORTING
    },
    isFirstLegRole,
    isFLOperate,
    getShipmentBGMethodStr,
    WAIT_FL_RECEIVE() {
      return WAIT_FL_RECEIVE
    },
    FINISHED_SHELVES() {
      return FINISHED_SHELVES
    },
    getShipmentTypeStr2,
    getShipmentStatus2Str,
    jumpPage,
    PLAN_TYPE_FL(){
      return PLAN_TYPE_FL
    },
    PLAN_TYPE_MW(){
      return PLAN_TYPE_MW
    },
    getShipmentStatusStr,
    getCombinationStatus,
    jumpCombinationInfo,
    getPlatformShortNameByAccountNum,
    getPlatformTextColor,
    getLabelStatusStr,
    getShipmentTypeStr,
    jumpLabelOrderInfo,
    showSaveBox(){
      // 不再判断入库箱子数 是否相等
      this.saveBox()
    },
    // 单独保存箱子
    saveBox(){
      this.boxLoading = true;
      const data = {
        id: this.data.id,
        shipmentBox: this.shipmentBox,
      }
      saveShipmentBox(data)
        .then(res=>{
          this.boxLoading = false;
          if(res.error === 0){
            this.$successMessage(res.message)
            this.$emit('changeData');
          }else{
            this.$errorMessage(res.message)
          }
        })
    },
    saveBoxV2(row){
      const data = {
        id: row.id,
        shipmentId: this.data.id,
        rlBoxNum: row.rlBoxNum,
      }
      saveShipmentBoxV2(data)
        .then(res=>{
          if(res.error === 0){
            row.save = 1
            this.$successMessage(res.message)
            // this.$emit('changeData');
          }
        })
    },
    changeShipmentPage(page){
      //this.showShipmentGoodsParams.page = page
    },

    // 合并单元格
    arraySpanMethod({ row, column, rowIndex, columnIndex }){
      if(this.data.status === 0){
        if (columnIndex === 3) {
          return [2, 1];
        }
      }
    },
    // 修改商品数
    editGoodsNum(row){
      row.isEdit = 1;
      setTimeout(()=>{
        this.$refs['goods'+row.id].focus();
      },0)
    },
    // 保存实际入库数量
    saveGoodsNum(row){
      if(row.exGoodsNum !== row.rlGoodsNum && !this.knowSku){
        const html = `
       <p><span style="color: #ff0000">${this.$t('shipment.saveSKUText1')}</span></p>
       <p style="margin-top: 20px"><span>${this.$t('shipment.saveSKUText2')}</span></p>
      `;
        this.$alert(
          html,
          this.$t('shipment.saveSKUTitle'),
          {
            dangerouslyUseHTMLString:true,
            // type:'warning',
            showCancelButton:true,
          }
        )
          .then(res=>{
            //
            this.saveGoodsNumStep2(row)
            this.knowSku = 1
          })
          .catch(res=>{
          })
      }else{
        this.saveGoodsNumStep2(row)
      }
    },
    saveGoodsNumStep2(row){
      const data = {
        id: row.id,
        rlGoodsNum: row.rlGoodsNum === undefined ? 0 : row.rlGoodsNum,
        rlGoodsBoxNum: row.rlGoodsBoxNum === undefined ? 0 : row.rlGoodsBoxNum,
        rlGoodsMixinNum: row.rlGoodsMixinNum === undefined ? 0 : row.rlGoodsMixinNum,
      }
      saveShipmentGoods(data)
        .then(res=>{
          if(res.error === 0){
            this.$successMessage(res.message)
            row.save = true
          }else{
            this.$errorMessage(res.message)
          }
        })
    },
    // 修改了实际的入库箱子数
    editRlGoodsBoxNum(row){
      if(this.data.labelOrder && this.data.labelOrder.status === 2 && row.isTB){
        return;
      }
      const currentNum = row.rlGoodsBoxNum * row.goodsNumInBox
      row.rlGoodsNum = Math.max(currentNum,row.rlGoodsNum)
      let currentSumBoxNum = this.shipmentGoods.reduce((prev,item) => {
        return prev + item.rlGoodsBoxNum
      },0);

      this.shipmentBox.some(box=>{
        if(box.boxType === 4){
          if(!box.rlBoxNum){
            box.rlBoxNum = 0;
          }
          box.rlBoxNum = Math.max(currentSumBoxNum,box.rlBoxNum)
          return true
        }
      })
    },
    // 计算实际入库数量
    getRlGoodsNum(row){
      if(this.data.labelOrder && this.data.labelOrder.status === 2 && row.isTB){
        return row.rlGoodsNum
      }
      if(!row.rlGoodsBoxNum){
        row.rlGoodsBoxNum = 0
      }
      if(!row.rlGoodsMixinNum){
        row.rlGoodsMixinNum = 0
      }
      let currentNum = row.rlGoodsBoxNum * row.goodsNumInBox
      currentNum = currentNum ? currentNum : 0
      currentNum += row.rlGoodsMixinNum
      row.rlGoodsNum = currentNum
      return currentNum
    },
    jumpLabelOrderInfoV2(id, tag){
      if(!isOneShippingRole()){
        return;
      }
      this.jumpLabelOrderInfo(id, tag)
    },
    jumpCombinationInfoV2(id, tag){
      if(isOneShippingRole() || isMiddleRole()){
        this.jumpCombinationInfo(id, tag)
      }
    },
    // 确认全部接受
    allReceive(){
      let title = '确认全部已接收?'
      let html = `<div>确认当前货件的所有箱唛已接收，变更为所有箱唛为已接收状态？</div>`
      html += `<div class="font-red">确认后货件状态将直接变更为“待装柜”，无需再操作下方的「确认接收」按钮</div>`
      this.$confirm(html,title,{
        dangerouslyUseHTMLString: true,
      })
        .then(()=>{
          allReceive(this.data.id)
            .then(res=>{
              if(res.error === 0){
                this.$successMessage(res.message)
                this.$emit('changeData')
              }else{
                this.$errorMessage(res.message)
              }
            })
        })
        .catch(()=>{})
    },
    // 全部已分拣
    allSorted(){
      let title = '确认全部已分拣？'
      let html = `<div>确认当前货件单的所有货件已分拣完毕，变更为所有箱唛为已分拣状态？</div>`
      html += `<div class="font-red">确认后货件单状态将直接变更为“已分拣”，无需再操作下方的「确认已分拣」按钮</div>`
      this.$confirm(html,title,{
        dangerouslyUseHTMLString: true,
      })
        .then(()=>{
          shipmentAllSorted(this.data.id)
            .then(res=>{
              if(res.error === 0){
                this.$successMessage(res.message)
                this.$emit('changeData')
              }else{
                this.$errorMessage(res.message)
              }
            })
        })
        .catch(()=>{})
    }

  }
}
</script>

<style scoped lang="scss">
.wrap {
  padding: 30px 30px;
  .header{
    //display: flex;
    //justify-content: space-between;
  }
  .content{
    padding: 20px 0 0;
  }
  .header-card{
    font-size: 14px;
    background-color: rgba(242, 242, 242, 1);
    p{
      margin: 10px 0;
      padding: 0;
    }
    .font-bold{
      font-weight: bold;
    }
    .true-number{
      color: #FF0000;
      font-weight: 600;
    }
  }
}
.goods-table{
  //width: 1800px;
  .goods-title{
    font-size: 14px;
  }
  .goods-attr{
    font-size: 13px;
    color: #7F7F7F;
  }
}
.table-tips{

}
.header-card{
  position: relative;
  .button{
    position: absolute;
    display: flex;
    flex-direction: column;
    right: 20px;
    top: 30px;
  }
}
.box-header{
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
}
</style>
